package com.flutter_yfree

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.WindowManager
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.PluginRegistry
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.*

/** YFlutterPlugin */
@SuppressLint("StaticFieldLeak")
public class YFlutterPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "YFreePlugin")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull methodCall: MethodCall, @NonNull result: Result) {
        val arguments = methodCall.arguments as? Map<*, *>
        when (methodCall.method) {
//            "yLog" ->
//                yFlutter.yLog(arguments!!["message"].toString())
//            "yDoCrash" -> {
//                val sb = StringBuilder()
//                sb.append("异常时间：")
//                sb.append(SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.CHINESE).format(Date()))
//                sb.append("\n设备：")
//                sb.append(Build.MANUFACTURER).append("_").append(Build.MODEL)
//                try {
//                    sb.append("\n设备识别码：")
//                    val imei = YDeviceUtils.getImei(yFlutter.context)
//                    sb.append(if (TextUtils.isEmpty(imei)) "" else imei).append("_").append(YDeviceUtils.getUniqueId(yFlutter))
//                } catch (ignored: Exception) {
//                }
//                sb.append("\napk版本号：")
//                sb.append(YVersionUtils.getVersionCode(yFlutter.context)).append("_").append(YVersionUtils.getVersionName(yFlutter.context))
//                sb.append("\n异常信息：${arguments!!["message"].toString()}")
//                val message = sb.toString()
//                YLogUtils.out(yFlutter, message)
//                yFlutter.yLog(message)
//                if (YConfig.commitErrorLog != null)
//                    yFlutter.yPost(YConfig.commitErrorLog, YJsonKV().put("msg", message), object : YAjaxCallBack<Any>(yFlutter, false) {
//                        override fun onSuccessed(p0: ArrayList<Any>) {}
//                    }, false)
//            }
//            "yRequestStorage" ->
//                yFlutter.yDoPermissionThing(object : YPermissionListener(yFlutter) {
//                    override fun onSuccessed() {
//                        if (yFlutter.yBasePath == null) {
//                            //                yFlutter.yBasePath = Environment.getExternalStorageDirectory().absolutePath + YConfig.PROJECTBASEDIR
//                            yFlutter.yBasePath = yFlutter.context.getExternalFilesDir(YConfig.YFreeDir)!!.absolutePath + YConfig.PROJECTBASEDIR
//                            val readyFile = File(yFlutter.yBasePath!!)
//                            if (!readyFile.exists() && !readyFile.mkdirs()) {
//                                yFlutter.yShowBuilder("初始化app目录失败，请检查存储空间！", DialogInterface.OnClickListener { dialog, which -> YActivityManager.finishApplication() }, null as DialogInterface.OnClickListener?, false)
//                            }
//                        }
//                        YCrashHandler.init(yFlutter)
//                        result.success(true)
//                    }
//
//                    override fun onFailed(requestCode: Int, deniedPermissions: MutableList<String>) {
//                        if (arguments!!["showFail"] as Boolean) super.onFailed(requestCode, deniedPermissions)
//                        result.success(false)
//                    }
//                }, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//            "yGetAppName" ->
//                result.success(YAppUtils.getAppName(yFlutter.context))
//            "yConfigIP" ->
//                YConfig.IP = arguments!!["ip"].toString()
//            "yConfigUpdateIP" ->
//                YConfig.UPDATEIP = arguments!!["updateIp"].toString()
//            "yGetDeviceID" ->
//                result.success(YDeviceUtils.getUniqueId(yFlutter))
//            "yToast" ->
//                yFlutter.yToast(arguments!!["message"].toString())
//            "yPost" -> {
//                val kv = YJsonKV()
//                (arguments!!["jkparam"] as? HashMap<*, *>)?.forEach {
//                    if (it.value is String) kv.put(it.key.toString(), it.value)
//                    else kv.put(it.key.toString(), it.value)
//                }
//                yFlutter.yPost(arguments["jkid"].toString(), kv, object : YAjaxCallBack<Any>(yFlutter, arguments["showErrorToast"] as Boolean) {
//                    override fun onSuccessed(results: ArrayList<Any>) {
//                        result.success(hashMapOf("code" to "1", "results" to Gson().toJson(results), "message" to null))
//                    }
//
//                    override fun onFail(response: Any?, throwable: Throwable?, code: String?, message: String?) {
//                        result.success(hashMapOf("code" to code, "results" to null, "message" to message))
//                    }
//                }, arguments["showProgress"] as Boolean)
//            }
//            "yAesEncode" ->
//                result.success(YAESCrypt(arguments!!["password"].toString()).encrypt(arguments["content"].toString()))
//            "yAesDecode" ->
//                result.success(YAESCrypt(arguments!!["password"].toString()).decrypt(arguments["content"].toString()))
//            "yIsNetAble" ->
//                result.success(YNetUtil.isNetAble(yFlutter.context))
//            "yShowBuilder" -> {
//                val message = arguments!!["message"].toString()
//                val posTitle = arguments["posTitle"].toString()
//                val negTitle = arguments["negTitle"].toString()
//                val hasCancelCallBack = arguments["hasCancelCallBack"] as Boolean
//                val cancelAble = arguments["cancelAble"] as Boolean
//                if (hasCancelCallBack) yFlutter.yShowBuilder(message, posTitle, negTitle, { _, _ -> result.success(1) }, { _, _ -> result.success(0) }, cancelAble)
//                else yFlutter.yShowBuilder(message, posTitle, negTitle, { _, _ -> result.success(1) }, null, cancelAble)
//            }
//            "yShowActionSheet" -> {
//                val message = arguments!!["message"].toString()
//                val actions = arguments["actions"] as ArrayList<String>
//                yFlutter.yShowActionSheet(message, actions.toArray(arrayOf<String>()), { actionSheet, index ->
//                    result.success(hashMapOf("index" to index, "action" to actions[index]))
//                }, "取消", null)
//            }
//            "yShowSelectBuilder" -> {
//                val message = arguments!!["message"].toString()
//                val actions = arguments["actions"] as ArrayList<String>
//                val cancelAble = arguments["cancelAble"] as Boolean
//                if (cancelAble) actions.add("取消")
//                yFlutter.yShowSelectBuilder(message, actions.toArray(arrayOf())) { dialog, index ->
//                    if (index < actions.size - 1)
//                        result.success(hashMapOf("index" to index, "action" to actions[index]))
//                    else result.success(null)
//                }
//            }
//            "yRunOnUIThread" ->
//                yFlutter.yRunOnUIThread(arguments!!["delay"].toString().toLong()) { result.success(null) }
//            "yCheckUpdate" ->
//                YUpdateUtils.checkUpdate(yFlutter)
//            "yFinishApplication" ->
//                YActivityManager.finishApplication()
//            "yBase64Encode" ->
//                result.success(Base64.encode(arguments!!["content"].toString().toByteArray(), Base64.DEFAULT))
//            "yBase64Decode" ->
//                result.success(String(Base64.decode(arguments!!["content"].toString(), Base64.DEFAULT)))
//            "ySave" ->
//                yFlutter.context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).edit().putString(arguments!!["key"].toString(), arguments["value"].toString()).apply()
//            "yRead" ->
//                result.success(yFlutter.context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).getString(arguments!!["key"].toString(), null))
//            "yDelete" ->
//                yFlutter.context.getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE).edit().remove(arguments!!["key"].toString()).apply()
//            "yRegisterBroadcast" -> {
//                val broadcastName = arguments!!["broadcastName"].toString()
//                yFlutter.yRegisterReceiver(broadcastName) { bundle ->
//                    yRunFlutter(arguments["pageName"].toString(), "onYReceiveBroadcast", hashMapOf(
//                            "broadcastName" to broadcastName,
//                            "broadcastParams" to if (bundle == null) null else bundle["broadcastParams"] as HashMap<*, *>)
//                    )
//                }
//            }
//            "ySendBroadcast" -> {
//                val broadcastName = arguments!!["broadcastName"].toString()
//                val broadcastParams = arguments["broadcastParams"] as? HashMap<*, *>
//                if (broadcastParams != null) {
//                    val bundle = Bundle()
//                    bundle.putSerializable("broadcastParams", broadcastParams)
//                    yFlutter.ySendBroadcast(broadcastName, bundle)
//                } else yFlutter.ySendBroadcast(broadcastName)
//            }
//            "yUnregisterReceiver" ->
//                yFlutter.yUnregisterReceiver(arguments!!["broadcastName"].toString())
//            "yShowProgress" ->
//                YProgressDialog.showProgress(yFlutter)
//            "yDismissProgress" ->
//                YProgressDialog.dismissProgress(yFlutter)
//            "yCopyClipBoard" ->
//                (yFlutter.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText("text", arguments!!["content"].toString()))
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    companion object {
        lateinit var flutterEngine: FlutterEngine

        fun registerWith(activity: FlutterActivity, flutterEngine: FlutterEngine) {
            this.flutterEngine = flutterEngine
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                activity.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
                activity.window.decorView.systemUiVisibility =
                    (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
                activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                activity.window.statusBarColor = Color.TRANSPARENT
                activity.window.navigationBarColor = Color.TRANSPARENT
            }
        }

        fun yRunFlutter(
            className: String,
            methodName: String,
            params: HashMap<*, *>? = null,
            callback: ((result: Any) -> Unit)? = null
        ) {
            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, className).invokeMethod(
                methodName,
                params,
                object : MethodChannel.Result {
                    override fun notImplemented() {}
                    override fun error(
                        errorCode: String,
                        errorMessage: String?,
                        errorDetails: Any?
                    ) {
                    }

                    override fun success(result: Any?) {
                        if (result != null) callback?.invoke(result)
                    }
                })
        }
    }
}